﻿using System.Windows.Forms;
using System.Diagnostics;
using SdmxMl.Common;
using SdmxMl.Structure;
using SdmxMl.Helper;
using SdmxMl.Manager;
using System.Xml;
using System;
using SdmxMl.Pdf;
using System.Collections.Generic;

namespace SdmxMl.UC
{
    public partial class UcArtefactAttributes : UcBaseAttrib
    {
        #region Constructor

        public UcArtefactAttributes()
        {
            InitializeComponent();
            customComboBoxName.DropDownControl = ucmlText;
            this.checkBoxIsFinal.CheckedChanged += new System.EventHandler(checkBoxIsFinal_CheckedChanged);
        }
        #endregion

        #region IsFinal

        private void IsFinalEditControls(bool isFinal)
        {
            bool enabled = isFinal == false;

            ucAgencyRef.IsFinal = isFinal;
            textBoxID.ReadOnly = isFinal;
            customComboBoxName.IsFinal = isFinal;
            comboMultiLinesDescr.IsFinal = isFinal;
            ucDatePickerFrom.IsFinal = isFinal;
            ucDatePickerTo.IsFinal = isFinal;
   
            ucVersion1.Enabled = enabled;
            textBoxUri.ReadOnly = isFinal;
            textBoxUrn.ReadOnly = isFinal;
            checkBoxIsExternalRef.Enabled = enabled;
            checkBoxIsPartial.Enabled = enabled;
            textBoxServiceUrl.ReadOnly = isFinal;
            textBoxStructure.ReadOnly = isFinal;

            // TODO: Get possibility to change isFinal from a Model
            // checkBoxIsFinal.Enabled = enabled;

        }
        #endregion

        #region Binding

        protected override void BindToControls()
        {
            // Do not treat ReportingTaxonomy
            if (ar is ReportingTaxonomyType)
                ar = null;

            if (ar != null)
            {
                inBinding = true;

                Visible = true;
                textBoxID.Text = ar.Id;
                ucVersion1.Version = ar.Version;
                customComboBoxName.Text = ar.Name.ToString();
                ucmlText.ML = ar.Name;
                comboMultiLinesDescr.ML = ar.Description;
                ucAgencyRef.Text = ar.AgencyId;
                ucDatePickerFrom.Date = ar.ValidFrom;
                ucDatePickerTo.Date = ar.ValidTo;
                checkBoxIsFinal.Checked = ar.IsFinal;
                checkBoxIsExternalRef.Checked = ar.IsExternalReference;
                textBoxUri.Text = ar.Uri;
                textBoxUrn.Text = ar.Urn;
                textBoxStructure.Text = ar.StructureUrl;
                textBoxServiceUrl.Text = ar.ServiceURL;
                checkBoxIsPartial.Checked = ar.IsPartial;

                // Do we allow editing. 
                IsFinalEditControls(_isFinal);

                // External Navigation Command
                buttonNavigateExternal.Visible = string.IsNullOrEmpty(ar.Uri) == false;
                buttonPdf.Visible = ar is KeyFamilyType || ar is ConceptSchemeType || ar is MetadataStructureDefinitionType;
                buttonGetExternal.Visible = ar.IsExternalReference;
                inBinding = false;

            }
            else
                Visible = false;
        }

        protected override void BindFromControls()
        {
            if (ar != null)
            {
                ar.Id = textBoxID.Text;
                ar.Version = ucVersion1.Version;
                ar.Name.UpdateForCurrentLanguage(customComboBoxName.Text);


                ar.AgencyId = ucAgencyRef.Text;
                ar.ValidFrom = ucDatePickerFrom.Date;
                ar.ValidTo = ucDatePickerTo.Date;
                ar.IsFinal = checkBoxIsFinal.Checked;
                ar.IsExternalReference = checkBoxIsExternalRef.Checked;
                ar.Uri = textBoxUri.Text;
                ar.Urn = textBoxUrn.Text;
                ar.ServiceURL = textBoxServiceUrl.Text;
                ar.StructureUrl = textBoxStructure.Text;
                ar.IsPartial = checkBoxIsPartial.Checked;
            }
        }
        #endregion

        private void buttonNavigateExternal_Click(object sender, EventArgs e)
        {

            try
            {
                // If URN try to get it if not already in memory
                ArtefactRefTyped art = UrnManager.UrnToArtefactRefTyped(ar.Uri);
                if (art != null)
                {
                    UrnParser p = new UrnParser(ar.Uri);

                    // If already in memory, navigate otherwhile get from regidtry
                    if (NavigationManager.LocatenavigateProject(art.Type, art.FullIdent, p) == null)
                        NavigationManager.NavigateWithRegistry(art.Type, art.FullIdent, true, p);
                }
                else
                {
                    // Try to process document
                    System.Diagnostics.Process myProc;
                    myProc = System.Diagnostics.Process.Start(ar.Uri);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void textBoxUri_TextChanged(object sender, EventArgs e)
        {
            // External Navigation Command
            ar.Uri = textBoxUri.Text;
            buttonNavigateExternal.Visible = textBoxUri.Text.Length > 0;
        }

        #region PDF Generation

        private void buttonPdf_Click(object sender, EventArgs e)
        {
            try
            {
                new SdmxMl.Helper.CWaitCursor();
                string appDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                string pathDoc = appDir + "\\Test.pdf";
                SmManager sm = ReferenceManager.GetSmContainerImage();

                if (ar is KeyFamilyType)
                {
                    PdfDsdGen pdfDsd = new PdfDsdGen(pathDoc, sm, ar.FullIdent, LangSupport.CurLang);
                }
                else if (ar is ConceptSchemeType)
                {
                    PdfConceptSchemeGen pdfCstGen = new PdfConceptSchemeGen(pathDoc, sm, ar.FullIdent, LangSupport.CurLang);
                }
                else if (ar is MetadataStructureDefinitionType)
                {
                    pdfMsdGen pdfMsd = new pdfMsdGen(pathDoc, sm, ar.FullIdent, LangSupport.CurLang);
                }

                // Start the process.
                Process.Start(pathDoc);

            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "PDF Generator Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        #endregion

        private void buttonGetExternal_Click(object sender, EventArgs e)
        {
            try
            {
                // Remove proxy
                if (theNode != null && theNode.Parent != null && theNode.Parent.Tag is ArtefactManager)
                {
                    ArtefactManager am = theNode.Parent.Tag as ArtefactManager;
                    if (am != null)
                    {
                        // Store artefact as treenode will change when deleted in main tree
                        Artefact arDeleted = theNode.Tag as Artefact;

                        // Load from registry
                        XmlDocument xDoc = Multiplexor.Mux.Instance.GetArtefact(arDeleted.ArType.ToString(), arDeleted.FullIdent);

                        // Remove actual from memory
                        am.DelChild(ar);
                        theNode.Parent.Nodes.Remove(theNode);

                        // Load in main tree
                        ReferenceManager.TreeMgr.LoadSdmxArtefact(null, true, xDoc);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
